<template>
  <div :class="['form-designer-content', {'grid-design': showGrid}]"
       ref="content" data-role="design-root" :style="containerStyle"/>
</template>
<script>
import {createProps} from '@/utils';
import {createFormDefinition, createFormView} from '@/components/hhd/design/FormDesigner/types';

export default {
  name: 'FormDesignerContainer',
  props: {
    showGrid: createProps(Boolean),
    selectedView: createProps(String),
    formDefinition: createProps(Object, createFormDefinition),
  },
  mounted() {
    this.bindListener();
  },
  data() {
    return {
      view: createFormView(),
      listener: undefined,
      lastView: undefined
    };
  },
  methods: {
    unbind() {
      this.listener && this.listener.disconnect && this.listener.disconnect();
    },
    bindListener() {
      this.$nextTick(() => {
        this.unbind();
        this.$nextTick(() => {
          this.doBindListener();
        });
      });
    },
    doBindListener() {
      this.listener = new MutationObserver(() => {
        if (this.view) {
          this.$nextTick(() => {
            this.view.html = this.$refs.content && this.$refs.content.innerHTML || '';
          });
        }
      });
      let config = {attributes: true, childList: true, subtree: true};
      this.listener.observe(this.$refs.content, config);
    },
  },
  computed: {
    containerStyle() {
      return {
        width: `${this.view && this.view.pageWidth || 960}px`
      };
    },
  },
  watch: {
    selectedView: {
      handler() {
        this.$nextTick(() => {
          let view = this.selectedView && this.formDefinition
              && this.formDefinition.views && this.formDefinition.views.find(v => v.id === this.selectedView)
              || undefined;
          if (!view) {
            this.$refs.content.innerHTML = '';
          } else {
            this.view = view;
            this.$refs.content.style.width = `${view.pageWidth}px`;
            this.$refs.content.innerHTML = this.view.html || '';
            this.$emit('rebind');
          }
        });
      },
      immediate: true,
    }
  }
};
</script>